package com.zzsy.shoppingpro.utils;

import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;

import com.zzsy.shoppingpro.app.Config;
import com.zzsy.shoppingpro.app.application;
import java.io.File;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;
import java.lang.Thread.UncaughtExceptionHandler;

public class CrashLog implements UncaughtExceptionHandler {

	 @Override
	    public void uncaughtException(Thread thread, Throwable ex) {
	        if(ex == null || TextUtils.isEmpty(application.getFilePath())){
	            return;
	        }
	        Writer writer = new StringWriter();
	        PrintWriter printWriter = new PrintWriter(writer);
	        ex.printStackTrace(printWriter);
	        Throwable cause = ex.getCause();
	        while (cause != null) {
	            cause.printStackTrace(printWriter);
	            cause = cause.getCause();
	        }
	        printWriter.close();
	        android.util.Log.e(Config.TAG,"crash----"+writer.toString());
	        String path = getCachePath();
	        if(path == null){
	            return;
	        }
	        File f = new File(path +"/"+ System.currentTimeMillis()+".txt");
	        try {
	            OutputStream out = new FileOutputStream(f);
	            out.write(writer.toString().getBytes());
	            out.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
//	        System.exit(0);//没有sdcard会导致闪退
	    }

	    public static String getCachePath() {
	        File dir = new File(application.getFilePath());
	        if(dir != null){
	            File f = new File(dir,"baihui_debug");
	            if(!f.exists()){
	                f.mkdirs();
	            }else if(!f.isDirectory()){
	                f.delete();
	                f.mkdirs();
	            }
	            return f.getAbsolutePath();
	        }
	        return null;
	    }

    /**
     * TextWatcher:限制2位小数点
     * Created by JinZhenkun on 2017/2/24.
     */

    public static class LimitTwoDecimal implements TextWatcher {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            String temp = s.toString();
            int posDot = temp.indexOf(".");
            if (posDot <= 0)
                return;
            if (temp.length() - posDot - 1 > 2) {
                s.delete(posDot + 3, posDot + 4);
            }
        }
    }
}
